package com.jeecg.edu.controller;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.Highchart;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSLog;
import org.jeecgframework.web.system.service.LogService;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.jeecg.edu.util.DateUtil;


/**
 * 日志处理类
 * 
 * @author 张代浩
 * 
 */
@Controller
@RequestMapping("/eduHchartsController")
public class EduHChartsController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(EduHChartsController.class);

    //用户浏览器统计分析的国际化KEY
    private static final String USER_BROWSER_ANALYSIS = "user.browser.analysis";
	private SystemService systemService;
	
	private LogService logService;

	@Autowired
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}
	
	@Autowired
	public void setLogService(LogService logService) {
		this.logService = logService;
	}


	
	
	/**
	 * 统计集合页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "statisticTabs")
	public ModelAndView statisticTabs(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/edu/hcharts/statisticTabs");
	}
	/**
	 * 用户浏览器使用统计图
	 * 
	 * @return
	 */
	@RequestMapping(params = "userBroswer")
	public ModelAndView userBroswer(String reportType, HttpServletRequest request) {
		request.setAttribute("reportType", reportType);
		if("pie".equals(reportType)){
			return new ModelAndView("com/jeecg/edu/hcharts/userBroswerPie");
		}else if("line".equals(reportType)) {
			return new ModelAndView("com/jeecg/edu/hcharts/eduLine");
		}
		return new ModelAndView("com/jeecg/edu/hcharts/userBroswer");
	}
	
	
	@RequestMapping(params = "online")
	@ResponseBody
	public AjaxJson online() {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "查询线上";
		Map<String, Object> map;
		@SuppressWarnings("rawtypes")
		List<Map> res=new ArrayList<Map>();
		try{
			String sql="SELECT a.code ,a.name FROM edu_on_line a ORDER BY CODE ASC ";
			List<Object> list=systemService.findListbySql(sql);
			if (list.size() > 0) {							
				for (Object object : list) {
					map = new HashMap<String, Object>();
					Object[] obj = (Object[]) object;
							map.put("code", obj[0]);
							map.put("name", obj[1]);
			                res.add(map) ;   
						}
				}																	
			j.setObj(res);
		}catch(Exception e){
			e.printStackTrace();
			message = "查询线上失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	@RequestMapping(params = "offline")
	@ResponseBody
	public AjaxJson offline() {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "查询线上";
		Map<String, Object> map;
		@SuppressWarnings("rawtypes")
		List<Map> res=new ArrayList<Map>();
		try{
			String sql="SELECT a.code ,a.name FROM edu_off_line a ORDER BY CODE ASC ";
			List<Object> list=systemService.findListbySql(sql);
			if (list.size() > 0) {							
				for (Object object : list) {
					map = new HashMap<String, Object>();
					Object[] obj = (Object[]) object;
							map.put("code", obj[0]);
							map.put("name", obj[1]);
			                res.add(map) ;   
						}
				}																	
			j.setObj(res);
		}catch(Exception e){
			e.printStackTrace();
			message = "查询线上失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	
	
	/**
	 * 报表数据生成
	 * 
	 * @return
	 */
	@RequestMapping(params = "chartsrBar")
	@ResponseBody
	public List<Highchart> getHchartsrBar( HttpServletRequest req, HttpServletResponse response) {
		
		String onLineId = req.getParameter("onLineId");
		String onLineName = req.getParameter("onLineName");
		String offLineId = req.getParameter("offLineId");
		String offLineName = req.getParameter("offLineName");
		String beginDate = req.getParameter("beginDate");
		String endDate = req.getParameter("endDate");
		String reportType = req.getParameter("reportType");

		if(onLineId == null && offLineId == null){
			return null;
			
		}
		
		String[] days=DateUtil.getDays(beginDate, endDate);
		
		List<Highchart> list = new ArrayList<Highchart>();
		
		if(onLineId != null ){
			String[] onLineIds = onLineId.split(",");
			String[] onLineNames = onLineName.split(",");
			StringBuffer bf;
			for(int i=0;i<onLineIds.length;i++){
				String id = onLineIds[i];
				String name = onLineNames[i];
				Highchart hc = new Highchart();
				String query =" SELECT days,SUM(ct) FROM "+
					"((SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct "+
					"FROM edu_early_industry a WHERE  FIND_IN_SET ('"+id+"',a.`on_line`) "+  
					"AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC) "+
					"UNION ALL "+
					"(SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct " + 
					"FROM edu_sign_industry a WHERE  FIND_IN_SET ('"+id+"',a.`on_line`) "+ 
					"AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC) "+
					"UNION ALL "+
					"(SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct "+
					"FROM edu_hobby_industry a WHERE  FIND_IN_SET ('"+id+"',a.`on_line`) " +
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC)) a "+
					" GROUP BY a.days  ORDER BY days ASC";
				 
				 
				List industrys =systemService.findListbySql(query);
				Long count = systemService.getCountForJdbc(" SELECT  COUNT(*) AS 'count' FROM edu_early_industry where 1=1 ");
				List lt = new ArrayList();
				List lt2 = new ArrayList();
				hc = new Highchart();
				hc.setName(name);
				hc.setType(reportType);
				Map<String, Object> map;
				//初始化数据
				for(int j=0;j<days.length;j++){
					map = new HashMap<String, Object>();
					map.put("name", days[j]);
					map.put("y", 0);
					map.put("percentage", 0);
					lt.add(map); 
					lt2.add(map); 
					
				}
				
								
				if (industrys.size() > 0) {							
					for (Object object : industrys) {
						map = new HashMap<String, Object>();
						Object[] obj = (Object[]) object;
							map.put("name", obj[0]);
							map.put("y", obj[1]);
							Integer groupCount = Integer.parseInt(obj[1].toString());
							Double  percentage = 0.0;
							if (count != null && count.intValue() != 0) {
								percentage = new Double(groupCount)/count;
							}
							map.put("percentage", percentage*100);
							for(int k=0;k<lt.size();k++){
								Map<String, Object> res = (Map<String, Object>)lt.get(k);
								String key = res.get("name").toString();
								if(key.equals(obj[0])){
									lt.remove(k);
									lt.add(k, map);
								}
							}
					}
				
			  }
				hc.setData(lt);
				list.add(hc);			
				
			}			
			
		}
		
		
		if(offLineId != null ){
			String[] offLineIds = offLineId.split(",");
			String[] offLineNames = offLineName.split(",");
			StringBuffer bf;
			for(int i=0;i<offLineIds.length;i++){
				String id = offLineIds[i];
				String name = offLineNames[i];
				Highchart hc = new Highchart();
				String query =" SELECT days,SUM(ct) FROM "+
					"((SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct "+
					"FROM edu_early_industry a WHERE  FIND_IN_SET ('"+id+"',a.`off_line`) "+  
					"AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC) "+
					"UNION ALL "+
					"(SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct " + 
					"FROM edu_sign_industry a WHERE  FIND_IN_SET ('"+id+"',a.`off_line`) "+ 
					"AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC) "+
					"UNION ALL "+
					"(SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*) ct "+
					"FROM edu_hobby_industry a WHERE  FIND_IN_SET ('"+id+"',a.`off_line`) " +
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') >=  "+ beginDate.replaceAll("-", "")+
					" AND  DATE_FORMAT( a.`create_date`,'%Y%m%d') <=  "+ endDate.replaceAll("-", "")+
					" GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC)) a "+
					" GROUP BY a.days  ORDER BY days ASC";
				 
				 
				List industrys =systemService.findListbySql(query);
				Long count = systemService.getCountForJdbc(" SELECT  COUNT(*) AS 'count' FROM edu_early_industry where 1=1 ");
				List lt = new ArrayList();
				List lt2 = new ArrayList();
				hc = new Highchart();
				hc.setName(name);
				hc.setType(reportType);
				Map<String, Object> map;
				//初始化数据
				for(int j=0;j<days.length;j++){
					map = new HashMap<String, Object>();
					map.put("name", days[j]);
					map.put("y", 0);
					map.put("percentage", 0);
					lt.add(map); 
					lt2.add(map); 
					
				}
				
								
				if (industrys.size() > 0) {							
					for (Object object : industrys) {
						map = new HashMap<String, Object>();
						Object[] obj = (Object[]) object;
							map.put("name", obj[0]);
							map.put("y", obj[1]);
							Integer groupCount = Integer.parseInt(obj[1].toString());
							Double  percentage = 0.0;
							if (count != null && count.intValue() != 0) {
								percentage = new Double(groupCount)/count;
							}
							map.put("percentage", percentage*100);
							for(int k=0;k<lt.size();k++){
								Map<String, Object> res = (Map<String, Object>)lt.get(k);
								String key = res.get("name").toString();
								if(key.equals(obj[0])){
									lt.remove(k);
									lt.add(k, map);
								}
							}
					}
				
			  }
				hc.setData(lt);
				list.add(hc);			
				
			}			
			
		}
							
		return list;
	}
	

	/**
	 * 报表数据生成
	 * 
	 * @return
	 */
	@RequestMapping(params = "getHchartsrBar")
	@ResponseBody
	public List<Highchart> getHchartsrBar(HttpServletRequest request,String reportType, HttpServletResponse response) {
		int[] days = {20170701,20170702,20170703,20170704,20170705,20170706,20170707};
		List<Highchart> list = new ArrayList<Highchart>();
		Highchart hc = new Highchart();
		String query = " SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*)  FROM edu_early_industry a WHERE  FIND_IN_SET ('02',a.`on_line`)  GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC ";
		List userBroswerList =systemService.findListbySql(query);
		Long count = systemService.getCountForJdbc(" SELECT  COUNT(*) AS 'count' FROM edu_early_industry where 1=1 ");
		List lt = new ArrayList();
		List lt2 = new ArrayList();
		hc = new Highchart();
		hc.setName(MutiLangUtil.getMutiLangInstance().getLang(USER_BROWSER_ANALYSIS));
		hc.setType(reportType);
		Map<String, Object> map;
		
		//初始化数据
		for(int i=0;i<days.length;i++){
			map = new HashMap<String, Object>();
			map.put("name", days[i]);
			map.put("y", 0);
			map.put("percentage", 0);
		    lt.add(map); 
		    lt2.add(map); 
			
		}
		
		
		if (userBroswerList.size() > 0) {							
				for (Object object : userBroswerList) {
					map = new HashMap<String, Object>();
					Object[] obj = (Object[]) object;
						map.put("name", obj[0]);
						map.put("y", obj[1]);
						Integer groupCount = Integer.parseInt(obj[1].toString());
						Double  percentage = 0.0;
						if (count != null && count.intValue() != 0) {
							percentage = new Double(groupCount)/count;
						}
						map.put("percentage", percentage*100);
						for(int i=0;i<lt.size();i++){
							Map<String, Object> res = (Map<String, Object>)lt.get(i);
							String key = res.get("name").toString();
							if(key.equals(obj[0])){
								lt.remove(i);
								lt.add(i, map);
							}
						}
				}
																	
			
		}
	
		
		
		
		Highchart hc2 = new Highchart();
		String query2 = " SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*)  FROM edu_early_industry a WHERE  FIND_IN_SET ('01',a.`on_line`)  GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC ";
		List userBroswerList2 =systemService.findListbySql(query2);
		Long count2 = systemService.getCountForJdbc(" SELECT  COUNT(*) AS 'count' FROM edu_early_industry where 1=1 ");
		
		hc2 = new Highchart();
		hc2.setName("222");
		hc2.setType(reportType);
		Map<String, Object> map2;
		if (userBroswerList2.size() > 0) {
			for (Object object : userBroswerList2) {
				map2 = new HashMap<String, Object>();
				Object[] obj = (Object[]) object;
				map2.put("name", obj[0]);
				map2.put("y", obj[1]);
				Integer groupCount = Integer.parseInt(obj[1].toString());
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map2.put("percentage", percentage*100);
				for(int i=0;i<lt2.size();i++){
					Map<String, Object> res = (Map<String, Object>)lt2.get(i);
					String key = res.get("name").toString();
					if(key.equals(obj[0])){
						lt2.remove(i);
						lt2.add(i, map2);
					}
				}
				
				//lt2.add(map2);
			}
		}
		hc2.setData(lt2);		
		hc.setData(lt);
		list.add(hc);
		list.add(hc2);
		return list;
	}
	
	
	public Map hchats(String reportType,String code){
		Map res =new HashMap();
		Highchart hc = new Highchart();
		String query = " SELECT DATE_FORMAT( a.`create_date`,'%Y%m%d') days ,COUNT(*)  FROM edu_early_industry a WHERE  FIND_IN_SET ('"+code+"',a.`on_line`)  GROUP BY  DATE_FORMAT( a.`create_date`,'%Y%m%d')  ORDER BY DATE_FORMAT( a.`create_date`,'%Y%m%d') ASC ";
		List userBroswerList =systemService.findListbySql(query);
		Long count = systemService.getCountForJdbc(" SELECT  COUNT(*) AS 'count' FROM edu_early_industry where 1=1 ");
		List lt = new ArrayList();
		hc = new Highchart();
		hc.setName(MutiLangUtil.getMutiLangInstance().getLang(USER_BROWSER_ANALYSIS));
		hc.setType(reportType);
		Map<String, Object> map;
		if (userBroswerList.size() > 0) {
			for (Object object : userBroswerList) {
				map = new HashMap<String, Object>();
				Object[] obj = (Object[]) object;
				map.put("name", obj[0]);
				map.put("y", obj[1]);
				Integer groupCount = Integer.parseInt(obj[1].toString());
				Double  percentage = 0.0;
				if (count != null && count.intValue() != 0) {
					percentage = new Double(groupCount)/count;
				}
				map.put("percentage", percentage*100);
				lt.add(map);
			}
		}
		
		res.put("hc", hc);
		res.put("lt", lt);
		return res;
		
		
	}
	
	

	/**
	 * hightchart导出图片
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(params = "export")
	public void export(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String type = request.getParameter("type");
		String svg = request.getParameter("svg");
		String filename = request.getParameter("filename");

		filename = filename == null ? "chart" : filename;
		ServletOutputStream out = response.getOutputStream();
		try {
			if (null != type && null != svg) {
				svg = svg.replaceAll(":rect", "rect");
				String ext = "";
				Transcoder t = null;
				if (type.equals("image/png")) {
					ext = "png";
					t = new PNGTranscoder();
				} else if (type.equals("image/jpeg")) {
					ext = "jpg";
					t = new JPEGTranscoder();
				} else if (type.equals("application/pdf")) {
					ext = "pdf";
					t = (Transcoder) new PDFTranscoder();
				} else if (type.equals("image/svg+xml"))
					ext = "svg";
				response.addHeader("Content-Disposition",
						"attachment; filename=" + new String(filename.getBytes("GBK"),"ISO-8859-1") + "." + ext);
				response.addHeader("Content-Type", type);

				if (null != t) {
					TranscoderInput input = new TranscoderInput(
							new StringReader(svg));
					TranscoderOutput output = new TranscoderOutput(out);

					try {
						t.transcode(input, output);
					} catch (TranscoderException e) {
						out.print("Problem transcoding stream. See the web logs for more details.");
						e.printStackTrace();
					}
				} else if (ext.equals("svg")) {
					// out.print(svg);
					OutputStreamWriter writer = new OutputStreamWriter(out,
							"UTF-8");
					writer.append(svg);
					writer.close();
				} else
					out.print("Invalid type: " + type);
			} else {
				response.addHeader("Content-Type", "text/html");
				out
						.println("Usage:\n\tParameter [svg]: The DOM Element to be converted."
								+ "\n\tParameter [type]: The destination MIME type for the elment to be transcoded.");
			}
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

}
